package com.zero.utils;


import com.alibaba.fastjson.JSON;
import com.zero.common.domain.Result;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/*
*   响应JSON数据给前端 的工具
* */
public class ResponseJsonUtil {              // 远程调用   而不是直接依赖     会员使用单车

//    @Resource
//    private HttpServletResponse response;

    /*
    *   响应给前端
    * */
    public static void responseToFront(Integer code, String msg, HttpServletResponse response){
        // 获取 response 响应对象 (获取不到响应对象 response，不管是下面这种方式，还是属性注入，都会报空指针异常，只能通过调用该方法的对象传 response 了)
//        HttpServletResponse response = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getResponse();

        // 设置响应数据编码
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json;charset=utf-8");

        PrintWriter writer =null;
        try {
            writer = response.getWriter();
        } catch (IOException e) {
            e.printStackTrace();
        }

        // 创建 返回结果
        Result result = new Result(code, msg);

        writer.write(JSON.toJSONString(result));

        writer.flush();
        writer.close();
    }

}
